from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from app import models


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        username = request.session.get('username', 0)
        user_object = models.UserInfo.objects.filter(username=username).first()
        # 管理员
        if 'admin' in str(username):
            sql = 'select * from app_admin where admin_name = %s'
            user_object = models.Admin.objects.raw(sql, [username, ])
            if user_object[0].manager == 1:
                request.admin = 'true'
            else:
                request.admin = 'false'
        # 普通用户
        else:
            sql = 'select * from app_userinfo where username = %s'
            user_object = models.UserInfo.objects.raw(sql, [username, ])
        request.obj = None
        if user_object:
            '''异常处理，针对管理员 普通用户的登录验证'''
            try:
                request.obj = user_object[0].username
            except Exception as e:
                request.obj = user_object[0].admin_name

        """检查白名单(没有登陆就可以访问的页面)"""
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not request.obj:
            return redirect('login')
